package models

import (
    "time"
)

// Order 结构体表示订单
type Order struct {
    ID            int       `json:"id"`
    UserID        int       `json:"user_id"`
    ProductID     int       `json:"product_id"`
    ProductName   string    `json:"product_name"`
    Quantity      int       `json:"quantity"`
    TotalAmount   float64   `json:"total_amount"`
    Status        string    `json:"status"`
    OrderDate     time.Time `json:"order_date"`
    Price         float64   `json:"price"`  // 新增字段
}


// 获取指定ID的订单
func GetOrderByID(id int) (Order, error) {
    var order Order
    err := db.QueryRow("SELECT id, user_id, product_id, product_name, quantity, price, total_amount, status, order_date FROM orders WHERE id = ?", id).
        Scan(&order.ID, &order.UserID, &order.ProductID, &order.ProductName, &order.Quantity, &order.Price, &order.TotalAmount, &order.Status, &order.OrderDate)
    if err != nil {
        return order, err
    }
    return order, nil
}


func AddOrder(o Order) (int64, error) {
    // 获取商品价格
    var price float64
    err := db.QueryRow("SELECT price FROM products WHERE id = ?", o.ProductID).Scan(&price)
    if err != nil {
        return 0, err
    }

    // 计算总金额
    o.TotalAmount = price * float64(o.Quantity)
    o.Price = price  // 保存商品的单价

    // 插入订单信息
    stmt, err := db.Prepare("INSERT INTO orders(user_id, total_amount, price, status, order_date) VALUES(?, ?, ?, ?, ?)")
    if err != nil {
        return 0, err
    }
    defer stmt.Close()

    result, err := stmt.Exec(o.UserID, o.TotalAmount, o.Price, o.Status, o.OrderDate)
    if err != nil {
        return 0, err
    }

    orderID, err := result.LastInsertId()
    if err != nil {
        return 0, err
    }

    // 插入订单商品信息
    stmt2, err := db.Prepare("INSERT INTO order_items(order_id, product_id, product_name, quantity, price) VALUES(?, ?, ?, ?, ?)")
    if err != nil {
        return 0, err
    }
    defer stmt2.Close()

    _, err = stmt2.Exec(orderID, o.ProductID, o.ProductName, o.Quantity, o.Price)  // 使用商品价格
    if err != nil {
        return 0, err
    }

    return orderID, nil
}



// 更新订单状态
func UpdateOrderStatus(orderID int, status string) error {
    stmt, err := db.Prepare("UPDATE orders SET status = ? WHERE id = ?")
    if err != nil {
        return err
    }
    defer stmt.Close()

    _, err = stmt.Exec(status, orderID)
    return err
}

// 删除订单
func DeleteOrder(id int) (int64, error) {
    stmt, err := db.Prepare("DELETE FROM orders WHERE id = ?")
    if err != nil {
        return 0, err
    }
    defer stmt.Close()

    result, err := stmt.Exec(id)
    if err != nil {
        return 0, err
    }

    // 获取删除的行数
    rowsAffected, err := result.RowsAffected()
    if err != nil {
        return 0, err
    }

    return rowsAffected, nil
}
// 获取所有订单及其商品
func GetOrders() ([]Order, error) {
    rows, err := db.Query(`
        SELECT o.id, o.user_id, oi.product_id, oi.product_name, oi.quantity, oi.price, o.total_amount, o.status, o.order_date
        FROM orders o
        JOIN order_items oi ON o.id = oi.order_id
    `)
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    var orders []Order
    for rows.Next() {
        var order Order
        err := rows.Scan(&order.ID, &order.UserID, &order.ProductID, &order.ProductName, &order.Quantity, &order.Price, &order.TotalAmount, &order.Status, &order.OrderDate)
        if err != nil {
            return nil, err
        }
        orders = append(orders, order)
    }
    return orders, nil
}


